﻿using SoldiHive.Core.Cache;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace SoldiHive.Core.NodeJs
{
	public class ScriptExecutor : IScriptExecutor
	{
		protected ICache cache;
		protected IScriptExecutorConfiguration configuration;

		public ScriptExecutor(ICache cache, IScriptExecutorConfiguration configuration)
		{
			this.configuration = configuration;
			this.cache = cache;
		}

		public string Execute(string scriptName, params object[] args)
		{
			var workingDirectory = Path.Combine(Environment.CurrentDirectory, this.configuration.ScriptsDirectory);

			var arguments = new List<string>();
			arguments.Add(scriptName);
			arguments.AddRange(args.Select(s => s.ToString()));

			var startInfo = new ProcessStartInfo
			{
				FileName = this.configuration.NodeExeFile,
				Arguments = string.Join(" ", arguments),
				WorkingDirectory = workingDirectory,
				UseShellExecute = false,
				RedirectStandardOutput = true,
				CreateNoWindow = true
			};

			var output = string.Empty;
			using (var process = Process.Start(startInfo))
			{
				while (!process.StandardOutput.EndOfStream)
				{
					output = process.StandardOutput.ReadLine();
				}
			}

			return output;
		}
	}
}
